package com.mikepenz.presenter.imp;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.mikepenz.app.R;
import com.mikepenz.bean.CardBean;
import com.mikepenz.interactor.CardListInteractor;
import com.mikepenz.interactor.imp.CardListInteractorImp;
import com.mikepenz.presenter.CardListPresenter;
import com.mikepenz.presenter.listener.RequestListener;
import com.mikepenz.utils.CookicUntil;
import com.mikepenz.view.CardListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/10/10.
 */
public class CardListPresenterImp implements CardListPresenter ,RequestListener<List<CardBean>> {

    Context c;
    CardListView view;
    CardListInteractor interactor;
    List<Map<String,Object>> data;
    int selected = 0;


    public CardListPresenterImp(Context c){
        this.c = c;
        this.view = ((CardListView) c);
        interactor = new CardListInteractorImp(c,this);
        data = new ArrayList<>();
    }

    @Override
    public void getCardList() {

        String userId = CookicUntil.getUser().getUserId();
        interactor.getCard(userId);
    }

    @Override
    public void setSelect(int i) {
        data.get(selected).put("isCheck",false);
        data.get(i).put("isCheck",true);
        this.selected = i;
        view.notifyDataSetChanged();
        CardBean cardBean = JSON.toJavaObject((JSON) JSON.toJSON(data.get(selected)),CardBean.class);
        if (cardBean!=null)
            CookicUntil.setCardBean(cardBean);

        ((Activity) c).finish();
    }

    @Override
    public void Success(String tag, List<CardBean> result) {
        if(result!=null){
            for(CardBean bean :result){
                String json = JSON.toJSONString(bean);
                Map<String,Object> map = (Map<String,Object>) JSON.parse(json);
                data.add(map);
            }
        }
        view.setDate(data);
        view.notifyDataSetChanged();
    }

    @Override
    public void Error(String tag, String error) {
        view.showError(error);
    }

    @Override
    public void Exception(String tag, VolleyError error) {
        view.showError(c.getString(R.string.system_error));
    }
}
